<template>
  <div class="reg">
    <div class="reg-title">
      <!-- keys: 1-注册店长，4-创建加盟商 -->
      <h1 v-if="keys==1">欢迎加入我们</h1>
      <h1 v-if="keys==4">加盟商入驻</h1>
    </div>
    <van-form @submit="onSubmit">
      <div class="reg-section">
        <div class="uploaders">
          <span class="shopimg" v-if="keys==1">店铺图片</span>
          <span class="shopimg" v-if="keys==4">用户头像</span>
          <van-uploader v-model="img" :after-read="afterRead" :before-read="beforeRead" name='0' multiple :max-count="1" :max-size="5120 * 1024" @oversize="onOversize" />
        </div>
        <van-field :border="false" v-model="shopname" type="text" placeholder="店铺名称" v-if="keys==1" :rules="[{ required: true }]" />
        <van-field :border="false" v-model="shop_manager" type="text" placeholder="店长姓名" v-if="keys==1" :rules="[{ required: true }]" />
        <van-field :border="false" v-model="user_name" type="text" placeholder="用户名或手机号码" v-if="keys==4" :rules="[{ required: true }]" />
        <van-field :border="false" v-model="spf_name" type="text" placeholder="加盟商全称" v-if="keys==4" :rules="[{ required: true }]" />
        <van-field :border="false" v-model="tel" type="tel" placeholder="手机号码" :rules="[{pattern:checktel, required: true,message: '格式错误！'}]" />
        <van-field :border="false" v-model="email" placeholder="电子邮箱" v-if="keys==4" :rules="[{pattern:checkemail, required: true,message: '格式错误！' }]" />
        <van-popover v-model="showTips" :actions="actions" placement="top-end" @select="onSelect()">
          <template #reference>
            <van-field :border="false" v-model="pwd" ref="pwds" type="password" placeholder="密码" :rules="[{pattern:checkpwd, required: true,message: '格式错误！' }]">
              <template #right-icon>
                <van-icon name="question" @click="onSelect()" />
              </template>
            </van-field>
          </template>
        </van-popover>
        <van-field :border="false" v-model="locations" placeholder="选择所在地区" readonly is-link arrow-direction="down" @click="showArea = true" :rules="[{ required: true}]" />
        <van-field :border="false" v-model="address" placeholder="详细地址" :rules="[{ required: true}]" />
        <van-field :border="false" v-model="joins" readonly placeholder="选择加盟商" is-link arrow-direction="down" @click="showPicker1 = true" v-if="keys==1" :rules="[{ required: true }]" />
        <van-field :border="false" v-model="summary" type="textarea" placeholder="简介" v-if="keys==4" rows="1" autosize :rules="[{ required: true }]" />
        <van-field :border="false" v-model="is_lease" readonly placeholder="是否租赁设备" is-link arrow-direction="down" @click="showSign(0)" v-if="keys==4" :rules="[{ required: true }]" />
        <van-field :border="false" v-model="facilitys" type="number" placeholder="租赁的设备数量" v-if="keys==4&&is_lease=='已租赁'" :rules="[{ required: true }]">
          <template #extra><span style="margin-left: 5px;">台</span></template>
        </van-field>
        <van-field :border="false" v-model="timelimit" readonly placeholder="租赁时限" is-link arrow-direction="down" @click="showSign(1)" v-if="keys==4&&is_lease=='已租赁'" :rules="[{ required: true }]" />
        <van-field :border="false" v-model="rent" type="number" placeholder="租金" v-if="keys==4&&is_lease=='已租赁'" :rules="[{ required: true }]">
          <template #extra><span style="margin-left: 5px;">元</span></template>
        </van-field>
        <van-field :border="false" v-model="deposit" type="number" placeholder="押金" v-if="keys==4&&is_lease=='已租赁'" :rules="[{ required: true }]">
          <template #extra><span style="margin-left: 5px;">元</span></template>
        </van-field>
        <div class="reg-tips"><span>请上传本人身份证、银行卡正反面和营业执照</span></div>
        <div class="uploaders1">
          <span class="shopimg">身份证正面</span>
          <van-uploader v-model="idcardimg1" name='1' :before-read="beforeRead" multiple :max-count="1" :after-read="afterRead" />
        </div>
        <div class="uploaders1">
          <span class="shopimg">身份证反面</span>
          <van-uploader v-model="idcardimg2" name='2' multiple :max-count="1" :after-read="afterRead" :before-read="beforeRead" />
        </div>
        <div class="uploaders1">
          <span class="shopimg">银行卡正面</span>
          <van-uploader v-model="bankcardimg1" name='3' multiple :max-count="1" :after-read="afterRead" :before-read="beforeRead" />
        </div>
        <div class="uploaders1">
          <span class="shopimg">银行卡反面</span>
          <van-uploader v-model="bankcardimg2" name='4' multiple :max-count="1" :after-read="afterRead" :before-read="beforeRead" />
        </div>
        <div class="uploaders1">
          <span class="shopimg">营业执照</span>
          <van-uploader v-model="licenseimg" name='5' multiple :max-count="1" :after-read="afterRead" :before-read="beforeRead" />
        </div>
        <van-button class="reg-section-adp" type="info" size="16px" color="#1BB89C" native-type="submit" block round v-if="keys==1?sub_title='注 册':sub_title='创 建'">{{sub_title}}</van-button>
        <div class="code-login">
          <div v-if="keys==1">
            <span>已有账号？</span>
            <router-link to="/pwdlogin"><span>去登录</span></router-link>
          </div>
          <div v-if="keys==4">
            <router-link to="/my"><span>暂不创建</span></router-link>
          </div>
        </div>
      </div>
    </van-form>
    <!-- 省/市/区列表 -->
    <van-popup v-model="showArea" position="bottom" round>
      <van-area :area-list="areaList" @confirm="onArea" @cancel="showArea = false" />
    </van-popup>
    <!-- 加盟商列表 -->
    <van-popup v-model="showPicker1" position="bottom" round>
      <van-picker show-toolbar :columns="franchisee" @confirm="onConfirm" @cancel="showPicker1 = false" />
    </van-popup>
    <!-- 租赁设备、租赁时限列表 -->
    <van-popup v-model="showLease" position="bottom" round>
      <van-picker show-toolbar :columns="leases" @confirm="setLeases" @cancel="showLease = false" />
    </van-popup>
  </div>
</template>

<script>
import { areaList } from "@vant/area-data";
import { Toast } from "vant";
import * as imageConversion from "image-conversion";
export default {
  name: "Register",
  data () {
    return {
      areaList,
      nowareaList: [],
      keys: 0,
      sign: 0,
      sub_title: "",
      shopname: "", //店铺名称
      shop_manager: "", //姓名
      spf_name: "", //加盟商名称
      user_name: "", //加盟商用户名
      email: "", //加盟商邮箱
      tel: "", //手机号
      pwd: "", // 密码
      address: "", // 详细地址
      locations: "", // 省市区
      summary: "", // 加盟商简介
      img: [], //店铺图片
      is_lease: "", //是否租赁设备
      timelimit_id: "", //租赁时限id
      timelimit: "", //租赁时限
      deposit: "", //押金
      rent: "", //租金
      facilitys: "", //租赁的设备数量
      joins: "", //加盟商列表
      joinsid: "", //加盟商编号
      idcardimg1: [], // 身份证正面
      idcardimg2: [], // 身份证反面
      bankcardimg1: [], // 银行卡正面
      bankcardimg2: [], // 银行卡反面
      licenseimg: [], // 营业执照
      checkemail: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/,
      checktel: /^1[3456789][0-9]{9}$/,
      checkpwd: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/,
      actions: [
        {
          text: "请设置由数字和大、小写字母组成的6-16位密码",
          className: "showTips",
        },
      ],
      showArea: false,
      showPicker1: false,
      showLease: false,
      showTips: false,
      franchisee: [],
      leases: [],
      spf_id: "",
      tt: "",
      datalist: {
        imagesurl: "", //商铺图片
        idcardimg1: "", //身份证正面
        idcardimg2: "", //身份证反面
        bankcardimg1: "", //银行卡正面
        bankcardimg2: "", //银行卡反面
        licenseimg: "", //营业执照照片
      },
    };
  },
  methods: {
    onOversize () {
      // 店铺图片限制
      Toast.fail("图片大小不能超过5M");
    },
    onSelect () {
      // 密码规则提示
      this.showTips = !this.showTips;
    },
    onConfirm (val) {
      // 确认选择加盟商
      this.showPicker1 = false;
      this.joins = val.text;
      this.joinsid = val.spf_id;
    },
    // 确认选择租赁设备、租赁时限
    setLeases (val) {
      this.showLease = false;
      if (this.sign == 0) {
        this.is_lease = val;
      } else {
        this.timelimit_id = val.id;
        this.timelimit = val.text;
      }
    },
    // 0:租赁设备、1:租赁时限  区分弹出层
    showSign (sign) {
      this.sign = sign
      this.showLease = true;
      if (this.sign == 0) {
        this.leases = ["已租赁", "未租赁"];
      } else {
        this.leases = [
          { id: 1, text: "月租" },
          { id: 2, text: "季租" },
          { id: 3, text: "年租" },
        ];
      }
    },
    beforeRead (file, detail) {
      imageConversion.compressAccurately(file, 100).then((res) => {
        res = new File([res], file.name, {
          type: res.type,
          lastModified: Date.now(),
        });
        var path = "";
        var d = detail.name;
        let params = new FormData();
        params.append("file", res);
        this.$notoken("/main/upload", params).then((res) => {
          path = res.data.data;
          if (d == 0) {
            this.datalist.imagesurl = path;
          } else if (d == 1) {
            this.datalist.idcardimg1 = path;
          } else if (d == 2) {
            this.datalist.idcardimg2 = path;
          } else if (d == 3) {
            this.datalist.bankcardimg1 = path;
          } else if (d == 4) {
            this.datalist.bankcardimg2 = path;
          } else if (d == 5) {
            this.datalist.licenseimg = path;
          }
        });
        file.status = "uploading";
        file.message = "上传中...";
        setTimeout(() => {
          file.status = "done";
          file.message = "上传成功";
        }, 1000);
      });
      return true
    },
    afterRead () {

    },
    onArea (val) {
      this.nowareaList = val;
      this.locations = val
        .filter((item) => !!item)
        .map((item) => item.name)
        .join("/");
      this.showArea = false;
    },
    FranchiseeList () {
      this.$notoken("/subplat/getsubplatlist", {
        type: 1,
      })
        .then((res) => {
          if (res.data.code == 1) {
            this.franchisee = res.data.data.map((item) => {
              return {
                ...item,
                text: item.spf_name,
                id: item.spf_id,
              };
            });
            var defaults = {
              id: "0",
              spf_id: "0",
              text: "总部",
            };
            this.franchisee.unshift(defaults);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 提交表单注册
    onSubmit () {
      //  keys: 1-注册店长，4-创建加盟商
      if (this.keys == 1) {
        var data1 = {
          shopname: this.shopname, //店铺名称
          shop_manager: this.shop_manager, //店长姓名
          user_name: this.tel, //用户名
          password: this.pwd, //密码
          province: this.nowareaList[0].name, //省
          city: this.nowareaList[1].name, //市
          area: this.nowareaList[2].name, //区
          address: this.address, //详细地址
          spf_id: this.joinsid, //经销商ID / 总部ID - 0
        };
        var zong1 = Object.assign(data1, this.datalist);
        this.$notoken("/weixin/register", zong1)
          .then((res) => {
            if (res.data.code == 1) {
              localStorage.setItem(
                "userInfo",
                JSON.stringify(res.data.data)
              );
              localStorage.setItem("token", res.data.data.token);
              localStorage.setItem("type", "1"); // 用于区分注册下单和普通下单
              Toast.success("提交成功\n请购买商品！");
              setTimeout(() => {
                this.$router.push({ path: "/regbuy" });
              }, 1500);
            } else {
              Toast.fail(res.data.msg);
            }
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        var data2 = {
          spf_name: this.spf_name, //加盟商名称
          phone: this.tel, //加盟商联系电话
          email: this.email, //电子邮箱，比如 example@qq.com
          summary: this.summary, //简介
          user_name: this.user_name, //用户名
          password: this.pwd, //密码
          province: this.nowareaList[0].name, //省
          city: this.nowareaList[1].name, //市
          area: this.nowareaList[2].name, //区
          address: this.address, //详细地址
          is_lease: this.is_lease == "已租赁" ? 1 : 2, //是否有租赁设备，1-租赁，2-未租赁
          timelimit: this.timelimit_id, //租赁时限
          num: this.facilitys, //设备数量
          rent: this.rent, // 租金
          cash_pledge: this.deposit, // 押金
        };
        var zong2 = Object.assign(data2, this.datalist);
        this.$axios("/subplat/boxesubplat", zong2)
          .then((res) => {
            if (res.data.code == 1) {
              Toast.success("创建成功");
              setTimeout(() => {
                this.$router.push({ name: "my" });
              }, 1500);
            } else {
              Toast.fail("该手机号已被注册，请更换手机号");
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
  },
  created () {
    this.keys = this.$route.params.keys;
  },
  mounted () {
    this.onSelect();
    this.FranchiseeList();
    setTimeout(() => {
      this.showTips = false;
    }, 8000);
  },
};
</script>

<style lang="less" scoped>
html,
body {
  width: 100%;
  height: 100%;
  background-color: #1bb89c;
}
.reg {
  display: flex;
  flex-direction: column;
  &-title {
    display: flex;
    width: 100%;
    height: 200px;
    background-color: #1bb89c;
    border-radius: 0 0 50px 50px;
    h1 {
      width: 100%;
      color: #fff;
      font-size: 45px;
      font-weight: normal;
      text-align: center;
      padding-top: 80px;
    }
  }
  .reg-section {
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 70%;
    padding: 50px 0;
    margin: 0 auto;
    .reg-tips {
      font-size: 30px;
      line-height: 50px;
      padding: 15px;
    }
    .uploaders {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .uploaders1 {
      display: flex;
      align-items: center;
      justify-content: space-around;
      margin: 20px 0;
    }
    .shopimg {
      font-size: 28px;

      margin: 0 70px 0 30px;
    }
    /deep/ .van-uploader__wrapper {
      justify-content: center;
    }
    /deep/ .van-uploader__upload,
    /deep/ .van-uploader__preview,
    /deep/ .van-uploader__preview-image {
      border-radius: 100px;
      margin: 0;
    }
    /deep/ .van-field {
      // height: 88px;
      margin: 0 auto 30px;
      background: transparent;
      border-bottom: 1px solid #ccc;
    }
    &-adp:first-child {
      margin-top: 25px;
    }
    &-adp {
      width: 70%;
      height: 88px;
      margin: 50px auto;
    }
    .code-login {
      display: flex;
      justify-content: flex-end;
      width: 450px;
      height: 30px;
      margin: 0 auto;
      font-weight: bold;
      font-size: 26px;
      text-align: right;
      a {
        color: #1bb89c;
      }
    }
  }
}
</style>